package com.xz.supplierOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.SecurityUtils;
import com.xz.product.mapper.ProductMapper;
import com.xz.product.vo.ProductRelatedInfoVo;
import com.xz.supplier.domain.Supplier;
import com.xz.supplier.mapper.SupplierMapper;
import com.xz.supplierOrder.domain.SupplierOrder;
import com.xz.supplierOrder.domain.SupplierOrderDetail;
import com.xz.supplierOrder.domain.SupplierOrderDetailRecord;
import com.xz.supplierOrder.dto.SupplierOrderDetailDto;
import com.xz.supplierOrder.dto.SupplierOrderDto;
import com.xz.supplierOrder.mapper.SupplierOrderDetailMapper;
import com.xz.supplierOrder.service.ISupplierOrderDetailService;
import com.xz.supplierOrder.vo.SupplierOrderDetailFlowReportVo;
import com.xz.supplierOrder.vo.SupplierOrderDetailFlowSummaryVo;
import com.xz.warehouse.service.IWarehouseService;
import jdk.nashorn.internal.objects.annotations.Where;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 贸易中间商订单商品Service业务层处理
 *
 * @author xz
 * @date 2024-02-27
 */
@Service
public class SupplierOrderDetailServiceImpl extends ServiceImpl<SupplierOrderDetailMapper, SupplierOrderDetail> implements ISupplierOrderDetailService {
  @Autowired
  private SupplierOrderDetailMapper supplierOrderDetailMapper;
  @Autowired
  private ProductMapper productMapper;
  @Autowired
  private SupplierMapper supplierMapper;
  /**
   * 查询贸易中间商订单商品
   *
   * @param id 贸易中间商订单商品主键
   * @return 贸易中间商订单商品
   */
  @Override
  public SupplierOrderDetail selectSupplierOrderDetailById(Long id) {
    return supplierOrderDetailMapper.selectSupplierOrderDetailById(id);
  }

  /**
   * 根据订单id查询贸易中间商订单商品
   *
   * @param orderId 订单id
   * @return 贸易中间商订单商品
   */
  @Override
  public List<SupplierOrderDetail> selectByOrderId(Long orderId) {
    return supplierOrderDetailMapper.selectList(
      new LambdaQueryWrapper<SupplierOrderDetail>()
        .eq(SupplierOrderDetail::getOrderId, orderId)
    );
  }

  @Override
  public void setRecordDetail(SupplierOrder supplierOrder, List<SupplierOrderDetailRecord> records) {
    // 查询对应的贸易中间商订单商品详情
    List<SupplierOrderDetail> details = selectByOrderId(supplierOrder.getId());
    //把详情塞入出库记录中，后续使用
    records.forEach(record->{
      details.forEach(detail->{
        if(record.getOrderDetailId().equals(detail.getId())){
          record.setDetail(detail);
        }
      });
    });
  }

  /**
   * 根据订单id，数据类型，查询贸易中间商订单商品
   *
   * @param orderId
   * @param dataType
   * @return
   */
  @Override
  public List<SupplierOrderDetail> selectByOrderIdAndDataType(Long orderId, Integer dataType) {
    return supplierOrderDetailMapper.selectList(
      new LambdaQueryWrapper<SupplierOrderDetail>()
        .eq(SupplierOrderDetail::getOrderId, orderId)
        .eq(SupplierOrderDetail::getDataType, dataType)
    );
  }


  /**
   * 流水报表
   *
   * @param supplierOrderDetail 贸易中间商订单商品
   * @return 贸易中间商订单商品
   */
  @Override
  public List<SupplierOrderDetailFlowReportVo> selectReport(SupplierOrderDetail supplierOrderDetail) {
    return supplierOrderDetailMapper.selectReport(supplierOrderDetail);
  }

  /**
   * 汇总报表
   *
   * @param supplierOrderDetail 贸易中间商订单商品
   * @return 贸易中间商订单商品
   */
  @Override
  public List<SupplierOrderDetailFlowSummaryVo> selectSummary(SupplierOrderDetail supplierOrderDetail) {
    Integer summaryQuantity = supplierOrderDetailMapper.selectSummaryQuantity(supplierOrderDetail);
    if (null == summaryQuantity || 0 == summaryQuantity) {
      return new ArrayList<>();
    }
    supplierOrderDetail.setSummaryQuantity(summaryQuantity);
    return supplierOrderDetailMapper.selectSummary(supplierOrderDetail);
  }

  /**
   * 查询贸易中间商订单商品列表
   *
   * @param supplierOrderDetail 贸易中间商订单商品
   * @return 贸易中间商订单商品
   */
  @Override
  public List<SupplierOrderDetail> selectSupplierOrderDetailList(SupplierOrderDetail supplierOrderDetail) {
    return supplierOrderDetailMapper.selectSupplierOrderDetailList(supplierOrderDetail);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insertBatchForOrder(SupplierOrder order, SupplierOrderDto dto) {
    //当前用户
    LoginUser user = SecurityUtils.getLoginUser();
    //开始新增数据
    List<SupplierOrderDetail> details = new ArrayList<>();
    //处理发货
    if (!CollectionUtils.isEmpty(dto.getDeliveryDetails())) {
      details.addAll(dto.getDeliveryDetails().stream().map(a -> initDetail(1, order, a, user)).collect(Collectors.toList()));
    }
    //处理退货数据
    if (!CollectionUtils.isEmpty(dto.getReturnDetails())) {
      details.addAll(dto.getReturnDetails().stream().map(a -> initDetail(2, order, a, user)).collect(Collectors.toList()));
    }
    //批量保存
    this.saveBatch(details);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateBatchForOrder(SupplierOrder order, SupplierOrderDto dto) {
    //当前用户
    LoginUser user = SecurityUtils.getLoginUser();
    List<SupplierOrderDetail> details = new ArrayList<>();

    //处理发货
    if (!CollectionUtils.isEmpty(dto.getDeliveryDetails())) {
      details.addAll(dto.getDeliveryDetails().stream().map(a -> initDetail(1, order, a, user)).collect(Collectors.toList()));
    }
    //处理退货数据
    if (!CollectionUtils.isEmpty(dto.getReturnDetails())) {
      details.addAll(dto.getReturnDetails().stream().map(a -> initDetail(2, order, a, user)).collect(Collectors.toList()));
    }

    //删除不在此次更新的旧数据
    List<Long> updateIds = details.stream().filter(a -> null != a.getId()).map(SupplierOrderDetail::getId).collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(updateIds)) {
      supplierOrderDetailMapper.delete(new LambdaQueryWrapper<SupplierOrderDetail>()
        .eq(SupplierOrderDetail::getOrderId, dto.getId()).notIn(SupplierOrderDetail::getId, updateIds));
    }

    //开始一一更新和插入数据
    details.forEach(detail -> {
      if (null == detail.getId()) {
        this.supplierOrderDetailMapper.insertSupplierOrderDetail(detail);
      } else {
        this.supplierOrderDetailMapper.updateSupplierOrderDetail(detail);
      }
    });
  }

  /**
   * 初始化详情数据
   *
   * @param dataType
   * @param order
   * @param detailDto
   * @param user
   */
  private SupplierOrderDetail initDetail(int dataType, SupplierOrder order, SupplierOrderDetailDto detailDto, LoginUser user) {

    SupplierOrderDetail detail = new SupplierOrderDetail();
    detail.setId(detailDto.getId());
    //订单相关字段
    detail.setOrderId(order.getId());
    detail.setDataType(dataType);
    detail.setEntSupplierId(order.getSupplierId());
    detail.setEntSupplierName(order.getSupplierName());
    //商品相关字段
    ProductRelatedInfoVo productVo = productMapper.getProductRelatedInfo(detailDto.getProductId());
    if (null == productVo) {
      throw new ServiceException("商品已删除：" + detailDto.getProdName());
    }

    detail.setProductId(productVo.getId());
    detail.setProductEncoded(productVo.getEncoded());
    detail.setProductName(productVo.getProductName());
    detail.setSeries(productVo.getSeries());
    detail.setSpecification(productVo.getSpecification());
    detail.setManufacturer(productVo.getManufacturer());
    detail.setRegistrationNo(productVo.getRegistrationNo());

    detail.setBrandId(productVo.getBrandId());
    detail.setBrandName(productVo.getBrandName());
    detail.setProdNameId(productVo.getProdNameId());
    detail.setProdName(productVo.getProdName());
    detail.setProductCategoryId(productVo.getCategoryId());
    detail.setProductCategory(productVo.getProductCategory());
    detail.setUnitId(productVo.getUnitId());
    detail.setUnit(productVo.getUnitName());

    //商品参数，属性拼装
    if (!CollectionUtils.isEmpty(detailDto.getPurchaseProductParamList())) {
      StringBuilder stringBuilder = new StringBuilder();
      detailDto.getPurchaseProductParamList().forEach(j -> {
        stringBuilder.append(j.getAttributeName() + "：" + j.getAttributeParameter() + "；");
      });
      detail.setProductParam(stringBuilder.toString());
    } else {
      detail.setProductParam(detailDto.getProductParam());
    }

    //生产信息，有效期
    detail.setBatchNumber(detailDto.getBatchNumber());
    detail.setBatchDate(detailDto.getBatchDate());
    detail.setValidity(detailDto.getValidity());
    //仓库相关字段
    detail.setWarehouseId(detailDto.getWarehouseId());
    detail.setWarehouseName(detailDto.getWarehouseName());
    //供应商相关字段
    detail.setSupplierId(detailDto.getSupplierId());
    if (null != detail.getSupplierId()) {
      Supplier supplier = supplierMapper.selectById(detail.getSupplierId());
      if (null != supplier.getUnitName()) {
        detail.setSupplierName(supplier.getUnitName());
      }
    }
    //商品单价
    detail.setProductPrice(detailDto.getProductPrice());
    //合同金额
    detail.setContractPrice(detailDto.getContractPrice());
    //商品数量
    detail.setProductNum(detailDto.getProductNum());
    //商品小计 = 合同金额 * 商品数量
    detail.setSubtotal(detail.getContractPrice().multiply(new BigDecimal(detail.getProductNum())));
    //用户在前端录入信息
    detail.setPatientName(detailDto.getPatientName());
    detail.setRemark(detailDto.getRemark());
    //创建人信息
    detail.setCreateBy(user.getUserId());
    detail.setCreateByName(user.getUsername());
    detail.setCreateTime(DateUtils.getNowDate());
    detail.setTenantId(user.getTenantId());
    detail.setDeptId(user.getDeptId());
    return detail;
  }

  /**
   * 批量删除贸易中间商订单商品
   *
   * @param ids 需要删除的贸易中间商订单商品主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteSupplierOrderDetailByIds(Long[] ids) {
    return supplierOrderDetailMapper.deleteSupplierOrderDetailByIds(ids);
  }

  /**
   * 删除贸易中间商订单商品信息
   *
   * @param id 贸易中间商订单商品主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteSupplierOrderDetailById(Long id) {
    return supplierOrderDetailMapper.deleteSupplierOrderDetailById(id);
  }
}
